package com.vogue.family.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityOptionsCompat;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tencent.mmkv.MMKV;
import com.vogue.family.R;
import com.vogue.family.ui.vm.SplashViewModel;

public class SplashActivity extends AppCompatActivity {

    private SplashViewModel viewModel;
    private MMKV kv = MMKV.defaultMMKV();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        viewModel=new ViewModelProvider(this).get(SplashViewModel.class);
        int delayToActivity = getResources().getInteger(R.integer.delay_in_seconds_to_close);

        new Handler().postDelayed(() -> {
            //check token 是否还有效
            viewModel.onLoadUserInfo();
        }, delayToActivity);

        viewModel.getErrorMsg().observe(this,s -> {
            Log.e(getClass().getName(),s+"");
            Toast.makeText(SplashActivity.this,s,Toast.LENGTH_LONG).show();
        });

        viewModel.getUserInfo().observe(this,user -> {
            kv.encode("userInfo",new Gson().toJson(user));
            showMain();
        });

    }
    private void showMain() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Bundle bundle = ActivityOptionsCompat.makeCustomAnimation(this,android.R.anim.fade_in, android.R.anim.fade_out).toBundle();
        startActivity(intent, bundle);
        finish();
    }
}